package com.sdy.usercenter.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.usercenter.biz.model.SysUserDept;
import com.sdy.usercenter.biz.model.vo.DeptVO;
import com.sdy.usercenter.biz.model.vo.LayTreeItem;
import com.sdy.usercenter.biz.model.vo.UserDeptInfoVo;
import com.sdy.usercenter.biz.service.SysDeptService;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.usercenter.biz.model.SysDept;
import com.sdy.common.model.Response;
import com.sdy.usercenter.web.constants.WebConstants;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
import com.sdy.mvc.controller.BaseController;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织机构信息表 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2019-06-14
 */
@Slf4j
@RestController
@RequestMapping("/sysDept")
public class SysDeptController extends BaseController {
    @Autowired
    private SysDeptService sysDeptService;
    
    @GetMapping("/get")
    public Response get(Integer id) {
        SysDept dept = sysDeptService.getById(id);
        if (dept.getCode().length() > 3) {
            SysDept parent = sysDeptService.getByCode(dept.getCode().substring(0, dept.getCode().length() - 3));
            if (parent != null) {
                dept.setParentName(parent.getName());
                dept.setParentType(parent.getType());
            }
        }
        List<SysDept> dl = sysDeptService.getDeptAccessorList(id);
        Collections.reverse(dl);
        dept.setFullName(dl.stream().map(SysDept::getAbbreviation).collect(Collectors.joining(" > ")));
        return Response.success(dept);
    }

    /**
     * 部门数据
     */
    @GetMapping("/listDept")
    public Response listDept(String keyword) {
        List<DeptVO> deptList = sysDeptService.listDept(keyword);
        return Response.success(deptList);
    }
    
    /**
     * 子部门数据
     */
    @GetMapping("/listSubDept")
    public Response listSubDept(Integer parentId) {
        List<DeptVO> children = sysDeptService.listSubDept(parentId);
        return Response.success(children);
    }

    /**
     * 分页数据
     * @param request
     * @param page [current, size]
     * @return
     */
    @GetMapping("/pageSubData")
    public Response pageSubData(HttpServletRequest request, Page<SysDept> page, Integer parentDeptId, String code) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        SysDept sysDept = sysDeptService.getById(parentDeptId);
        wrapper.likeRight(SysDept::getCode, sysDept.getCode());
        wrapper.eq(SysDept::getLevel, sysDept.getLevel() + 1);
        wrapper.eq(StringUtil.isNotBlank(code), SysDept::getCode, code);
        wrapper.orderByAsc(SysDept::getCode);

        IPage<SysDept> result = sysDeptService.page(page, wrapper);
        return Response.success(result);
    }

    /**
     * 部门管理员
     */
    @GetMapping("/managerPageData")
    public Response managerPageData(HttpServletRequest request, Page<SysUserDept> page, Integer deptId) {
        if (deptId == null) {
            return Response.success(new Page<UserDeptInfoVo>(1, 1, 0).setRecords(new ArrayList<>()));
        }
        Map<String, Object> queryMap = new HashMap<>();
        IPage<UserDeptInfoVo> result = sysDeptService.managerPageData(page, queryMap, deptId);
        return Response.success(result);
    }

    /**
     * 部门下的用户
     */
    @GetMapping("/userPageData")
    public Response userPageData(HttpServletRequest request, Page<SysUserDept> page, Integer deptId) {
        if (deptId == null) {
            return Response.success(new Page<UserDeptInfoVo>(1, 1, 0).setRecords(new ArrayList<>()));
        }
        Map<String, Object> queryMap = new HashMap<>();
        IPage<UserDeptInfoVo> result = sysDeptService.userPageData(page, queryMap, deptId);
        return Response.success(result);
    }

    /**
     * 保存数据
     * @param
     * @return
     */
    @PostMapping("/save")
    public Response save(HttpServletRequest request, @RequestBody SysDept sysDept) throws BizException {
        String code = sysDept.getCode();
        SysDept parentDept = sysDeptService.getById(sysDept.getParentId());
        Assert.isNull(parentDept, "父项目数据不存在");
        Assert.isNull(sysDept.getType(), "请选择分类");
        Assert.isNull(sysDept.getClazz(), "请选择行政级别");
        Assert.isTrue(code.length() - parentDept.getCode().length() != 3, "组织编码长度不正确");
        Assert.isTrue(!code.startsWith(parentDept.getCode()), "组织编码不正确");
        Assert.isTrue(sysDeptService.getByCode(code) != null, "组织编码已存在");
        sysDept.setLevel(parentDept.getLevel() + 1);
        sysDeptService.save(sysDept.setCreateTime(new Date()));
        return Response.success(sysDept);
    }

    /**
     * 更新数据
     * @param
     * @return
     */
    @PostMapping("/update")
    public Response update(HttpServletRequest request, @RequestBody SysDept sysDept) throws BizException {
        Map<String, Object> result = new HashMap<>();
        String code = sysDept.getCode();
        Assert.isBlank(code, "组织代码不能为空");
        Assert.isNull(sysDept.getType(), "请选择分类");
        Assert.isNull(sysDept.getClazz(), "请选择行政级别");
        Assert.isTrue(sysDeptService.lambdaQuery().eq(SysDept::getCode, code).ne(SysDept::getId, sysDept.getId()).count() > 0, "组织编码已存在");
        var origin = sysDeptService.getById(sysDept.getId());
        var originParent = sysDeptService.getByCode(origin.getCode().substring(0, sysDept.getCode().length() - 3));
        if (originParent != null) {
            Assert.isTrue(code.length() - originParent.getCode().length() != 3, "组织编码长度不正确");
            Assert.isTrue(!code.startsWith(originParent.getCode()), "组织编码不正确");
            sysDept.setLevel(originParent.getLevel() + 1);
        } else {
            Assert.isTrue(code.length() != 3, "组织编码长度不正确");
            sysDept.setLevel(1);
        }
        sysDeptService.updateDept(sysDept);
        // 修改用户名
        return Response.success();
    }

    /**
     * 删除数据
     * @param id 主键
     * @return
     */
    @GetMapping("/delete")
    public Response delete(Integer id) {
        SysDept dept = sysDeptService.getById(id);
        sysDeptService.remove(new LambdaQueryWrapper<SysDept>().likeRight(SysDept::getCode, dept.getCode()));
        return Response.success();
    }

    /**
     * 删除数据
     * @param idList 主键
     * @return
     */
    @PostMapping("/deleteBatch")
    public Response deleteBatch(@RequestBody List<Integer> idList) {
        if (idList != null && !idList.isEmpty()) {
            idList.forEach(this::delete);
        }
        return Response.success();
    }

    /**
     * 
     */
    @PostMapping("/addManagerBatch")
    @ResponseBody
    public Response addManagerBatch(@RequestBody List<Integer> idList, Integer deptId) {
        int count = 0;
        if (idList != null && !idList.isEmpty()) {
            count = sysDeptService.addManagerBatch(idList, deptId);
        }
        return Response.success(count);
    }

    /**
     *
     */
    @PostMapping("/delManagerBatch")
    @ResponseBody
    public Response delManagerBatch(@RequestBody List<Integer> idList, Integer deptId) {
        int count = 0;
        if (idList != null && !idList.isEmpty()) {
            count = sysDeptService.delManagerBatch(idList, deptId);
        }
        return Response.success(count);
    }
}
